// 导入数据库模块
const { db, readDatabase, writeDatabase } = require('./db');

// 角色模型类
class CharacterModel {
  // 获取所有角色
  getAllCharacters(filters = {}) {
    readDatabase();
    let characters = db.data.characters || [];

    // 应用筛选条件
    if (filters.category) {
      characters = characters.filter(character => 
        character.categories && character.categories.includes(filters.category)
      );
    }

    if (filters.search) {
      const searchTerm = filters.search.toLowerCase();
      characters = characters.filter(character => 
        character.name.toLowerCase().includes(searchTerm) ||
        character.description.toLowerCase().includes(searchTerm) ||
        character.personality.toLowerCase().includes(searchTerm)
      );
    }

    return characters;
  }

  // 根据ID获取角色
  getCharacterById(id) {
    readDatabase();
    return db.data.characters.find(character => character.id === id);
  }

  // 创建新角色
  createCharacter(characterData) {
    readDatabase();
    
    // 检查角色名称是否已存在
    const existingCharacter = db.data.characters.find(
      character => character.name === characterData.name
    );
    if (existingCharacter) {
      throw new Error('角色名称已存在');
    }

    // 创建新角色对象
    const newCharacter = {
      id: db.data.characters.length > 0 ? Math.max(...db.data.characters.map(char => char.id)) + 1 : 1,
      name: characterData.name,
      description: characterData.description || '',
      personality: characterData.personality || '',
      avatar: characterData.avatar || '',
      categories: characterData.categories || [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    // 添加到数据库
    db.data.characters.push(newCharacter);
    writeDatabase();

    return newCharacter;
  }

  // 更新角色信息
  updateCharacter(id, characterData) {
    readDatabase();
    
    const characterIndex = db.data.characters.findIndex(char => char.id === id);
    if (characterIndex === -1) {
      throw new Error('角色不存在');
    }

    const character = db.data.characters[characterIndex];
    
    // 如果更新了角色名称，检查是否已存在
    if (characterData.name && characterData.name !== character.name) {
      const existingCharacter = db.data.characters.find(
        char => char.name === characterData.name
      );
      if (existingCharacter) {
        throw new Error('角色名称已存在');
      }
      character.name = characterData.name;
    }

    // 更新其他字段
    if (characterData.description !== undefined) {
      character.description = characterData.description;
    }
    if (characterData.personality !== undefined) {
      character.personality = characterData.personality;
    }
    if (characterData.avatar !== undefined) {
      character.avatar = characterData.avatar;
    }
    if (characterData.categories !== undefined) {
      character.categories = characterData.categories;
    }

    // 更新时间戳
    character.updatedAt = new Date().toISOString();

    // 保存更新
    writeDatabase();

    return character;
  }

  // 删除角色
  deleteCharacter(id) {
    readDatabase();
    
    const characterIndex = db.data.characters.findIndex(char => char.id === id);
    if (characterIndex === -1) {
      throw new Error('角色不存在');
    }

    // 删除角色
    const deletedCharacter = db.data.characters.splice(characterIndex, 1)[0];
    writeDatabase();

    return deletedCharacter;
  }

  // 获取所有角色分类
  getCharacterCategories() {
    readDatabase();
    const categories = new Set();
    
    db.data.characters.forEach(character => {
      if (character.categories) {
        character.categories.forEach(category => {
          categories.add(category);
        });
      }
    });

    return Array.from(categories);
  }

  // 搜索角色
  searchCharacters(query) {
    return this.getAllCharacters({ search: query });
  }
}

// 导出角色模型实例
module.exports = new CharacterModel();